#include "groupchat.h"
#include "ui_groupchat.h"
#include <QTime>
#include <QFile>
#include <QFileDialog>
#include <QScrollBar>
#include "sockethandler.h"

GroupChat::GroupChat(QString sender, QString groupName, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::GroupChat), sender(sender), groupName(groupName)
{
    ui->setupUi(this);
    this->setWindowTitle(sender + "的" + groupName + "群聊");
    this->ui->label_name->setText(groupName);
//    ui->te_chatFrame->setReadOnly(true);
    this->setFixedSize(this->geometry().size()); // 禁止窗口尺寸改变


    ui->scrollArea->setWidgetResizable(true);
    QWidget *scrollContent = new QWidget();
    QVBoxLayout *scrollLayout = new QVBoxLayout(scrollContent);
    // 设置QScrollArea内部QWidget的布局边距为0，减少额外空间影响
    scrollLayout->setContentsMargins(0, 0, 0, 0);
    scrollLayout->setSpacing(0);
    ui->scrollArea->setWidget(scrollContent);

    chatHistoryLayout = scrollLayout;
}

GroupChat::~GroupChat()
{
    delete ui;
}

void GroupChat::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event)
    emit chatClose(groupName);
    this->hide();
}


// 发送消息槽函数
void GroupChat::on_ptn_send_clicked()
{
    QString info = ui->te_info->toPlainText();
    if (info.isEmpty())
    {
        return ;
    }
    QString time = QTime::currentTime().toString();


    QGroupBox *myMessageBox = createMessageBox(sender, info, time);
    chatHistoryLayout->addWidget(myMessageBox);
    widgetVisible();

    ui->te_info->clear();
    emit sendInfo(sender, groupName, info, time);
}

// 接收消息槽函数
void GroupChat::onNewGroupInfo(messagePackage pack)
{
    QGroupBox *myMessageBox = createMessageBox(pack.sender(), pack.info(), pack.time());
    chatHistoryLayout->addWidget(myMessageBox);
    widgetVisible();
}

void GroupChat::on_btn_invite_clicked()
{
    QString name = ui->le_name->text();
    if (name.isEmpty())
    {
        return ;
    }
    ui->le_name->clear();
    emit inviteGroup(name, groupName);
}

void GroupChat::on_btn_share_clicked()
{
    QString filePath = QFileDialog::getOpenFileName(this, "上传文件", "../MeetingClient/file/", "ALL (*.*)");
    if (filePath.isEmpty()) return ;
    QString fileName = QFileInfo(filePath).fileName();
    //qDebug() << "filePath" << filePath;
    //qDebug() << "fileName" << fileName;
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly))
    {
        //qDebug() << "无法打开文件:" << filePath;
        return ;
    }
    QByteArray fileData = file.readAll();

    messagePackage pack;
    pack.setType(messagePackage::GroupFile);
    pack.setGroupName(groupName);
    pack.setFileName(fileName);
    pack.setFileData(fileData);
    pack.setSender(sender);

    messagePackage::sendMessage(&pack, socketHandler::getInstance()->getSocket());

    file.close();
}

QGroupBox *GroupChat::createMessageBox(const QString &sender, const QString &message, const QString &time)
{
    QGroupBox *messageBox = new QGroupBox(this);
    QVBoxLayout *layout = new QVBoxLayout(messageBox);
    messageBox->setMaximumHeight(76);
    messageBox->setAlignment(Qt::AlignTop);


    QLabel *senderLabel = new QLabel(sender + " " + time, this);
    QLabel *messageLabel = new QLabel(message, this);
    messageLabel->setWordWrap(true);
    messageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    layout->addWidget(senderLabel);
    layout->addWidget(messageLabel);

    if (sender == this->sender) {
        // 自己发送的消息，设置右对齐样式
        messageLabel->setAlignment(Qt::AlignRight);
        senderLabel->setAlignment(Qt::AlignRight);
        messageLabel->setText(message);
        messageBox->setStyleSheet("QGroupBox { border: 1px solid gray; border - radius: 5px; margin: 5px; padding: 5px; "
                                  "background-color: lightBlue; align - right: 0; }");
    } else {
        // 其他人发送的消息，设置左对齐样式
        messageBox->setStyleSheet("QGroupBox { border: 1px solid gray; border - radius: 5px; margin: 5px; padding: 5px; "
                                  "background-color: lightGreen; align - left: 0; }");
    }

    return messageBox;
}

void GroupChat::widgetVisible()
{
    QScrollBar *verticalScrollBar = ui->scrollArea->verticalScrollBar();
    QCoreApplication::processEvents();
    verticalScrollBar->setValue(verticalScrollBar->maximum()/* + 76*/);

}
